package com.example.everying.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.everying.constant.OrderConstants;
import com.example.everying.framework.pay.service.WechatTransferService;
import com.example.everying.model.dto.pay.TransferBillStatus;
import com.example.everying.model.dto.pay.TransferToUserResponse;
import com.example.everying.model.entity.pay.TransferBatchEntity;
import com.example.everying.model.entity.user.UserBalanceEntity;
import com.example.everying.model.entity.user.UserBalanceTransactionEntity;
import com.example.everying.model.entity.user.UserEntity;
import com.example.everying.service.pay.TransferBatchService;
import com.example.everying.service.user.UserBalanceService;
import com.example.everying.service.user.UserBalanceTransactionService;
import com.example.everying.service.user.UserService;
import com.wechat.pay.java.service.transferbatch.model.TransferDetailEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * @program: everying-java
 * @description: 提现定时任务
 * @author: szy
 * @create: 2025-09-23 08:58
 **/

@Component
@Slf4j
public class TransferStatusCheckTask {

    @Autowired
    private TransferBatchService transferBatchService;

    @Autowired
    private WechatTransferService wechatTransferService;

    @Autowired
    private UserBalanceService userBalanceService;

    @Autowired
    private UserBalanceTransactionService userBalanceTransactionService;

    @Autowired
    private UserService userService;

    /**
     * 定时检查超过30分钟仍未处理的转账批次
     */
    @Scheduled(fixedRate = 300000) // 每5分钟执行一次
    @Transactional
    public void checkPendingTransfers() {
        log.info("开始检查未完成的转账批次");

// 查询30分钟前创建且状态为PENDING或PROCESSING的批次
        LocalDateTime thirtyMinutesAgo = LocalDateTime.now().minusMinutes(30);
        LocalDateTime now = LocalDateTime.now();
        QueryWrapper<TransferBatchEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lt("create_time", now);  // 创建时间小于当前时间
        queryWrapper.gt("create_time", thirtyMinutesAgo);  // 创建时间大于30分钟前
        queryWrapper.in("batch_status", Arrays.asList("PENDING", "PROCESSING"));  // 添加PROCESSING状态

        List<TransferBatchEntity> pendingBatches = transferBatchService.list(queryWrapper);

        if (pendingBatches.isEmpty()) {
            log.info("没有未完成的转账批次");
            return;
        }

        for (TransferBatchEntity batch : pendingBatches) {
            try {
                // 主动查询微信转账状态
                checkAndHandleTransferStatus(batch);
            } catch (Exception e) {
                log.error("检查转账批次状态时出错，批次号: {}", batch.getBatchNo(), e);
            }
        }

        log.info("完成检查未完成的转账批次，共处理 {} 条", pendingBatches.size());
    }

    /**
     * 主动查询并处理转账状态
     */
    @Transactional
    protected void checkAndHandleTransferStatus(TransferBatchEntity batch) {
        try {
            // 调用微信接口查询转账状态
            TransferToUserResponse response = wechatTransferService.queryTransferBillByOutNo(batch.getBatchNo());

            if (response != null) {
                TransferBillStatus state = response.getState();

                if (TransferBillStatus.SUCCESS.equals(state)) {
                    // 转账成功，更新状态
                    transferBatchService.handleSuccessfulTransfer(batch, response);
                } else if (TransferBillStatus.isFailedOrClosed(state)) {
                    // 转账失败，需要回滚余额
                    transferBatchService.handleFailedTransfer(batch);
                }
                // 如果还是处理中状态，则继续等待
                log.info("转账批次继续等待，批次号: {}", batch.getBatchNo());
            } else {
                // 查询失败，可以考虑重试几次后标记为异常
                log.warn("查询转账状态失败，批次号: {}", batch.getBatchNo());
            }
        } catch (Exception e) {
            log.error("查询转账状态异常，批次号: {}", batch.getBatchNo(), e);
        }
    }




}